package com.itzyf.pokemondata.activity.gallery

import android.content.Intent
import com.avos.avoscloud.AVException
import com.avos.avoscloud.AVObject
import com.avos.avoscloud.AVQuery
import com.avos.avoscloud.GetCallback
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.DbComprehensiveDo
import com.tydic.baselibrary.activity.BaseActivity
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.callback.OnImageClickListener
import kotlinx.android.synthetic.main.activity_markdown.*
import org.litepal.LitePal


class MarkdownActivity : BaseActivity() {
    override fun handlerActivity() {
        RichText.initCacheDir(this)
        setTitle(intent.getStringExtra("title"))

        val findFirst = LitePal.where("objectId = ?", intent.getStringExtra("objId"))
            .findFirst(DbComprehensiveDo::class.java)
        if (findFirst != null) {
            setTitle(findFirst.name)
            setContent(findFirst.content)
        } else {
            showProgressDialog()
            val query = AVQuery<AVObject>("comprehensive")
            query.getInBackground(intent.getStringExtra("objId"), object : GetCallback<AVObject>() {
                override fun done(obj: AVObject?, e: AVException?) {
                    dismissProgressDialog()
                    if (obj != null) {
                        setTitle(obj.getString("name"))
                        setContent(obj.getString("content"))
                    }
                }
            })
        }
    }

    private fun setContent(text: String) {
        RichText
            .fromMarkdown(text)
            .imageClick { imageUrls, position ->
                run {
                    val intent = Intent(this@MarkdownActivity, ImageZoomActivity::class.java)
                    intent.putExtra("title", "查看图片")
                    intent.putExtra("image", imageUrls[position])
                    startActivity(intent)
                }
            }
            .into(content)
    }

    override fun getContentViewId() = R.layout.activity_markdown

    override fun getToolbarTitle() = ""

}